var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
var formTerm = {};  // 查询条件
var userList = getAllUser();
let startTime = 0;
let endTime = 0;
let bpmId = '';
let bpmStatus = '0';//审批状态  0 未审核 1 审批中 2审核完成
let isMsn="否";
layer.ready(function () {
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })
})
// function getNowMonth() {
//     $.ajax({
//         async:false,
//         type: 'POST',
//         url: 'number/getNowMonthNew',
//         dataType: "json",
//         contentType: 'application/json;charset=utf-8',
//         success: function (res) {
//             if (res.status == 200) {
//                 if (res.data != "") {
//                     startTime = res.data.startDate;
//                     endTime = res.data.endDate;
//                 }
//             } else {
//                 layer.msg(res.msg, {icon: 5});
//             }
//         },
//         error: function (data) {
//             layer.msg(data.msg, {icon: 5});
//         }
//     });
// }
//
// getNowMonth();

startTime = new Date(new Date().getFullYear(),new Date().getMonth(),1)
endTime = new Date(new Date().getFullYear(),new Date().getMonth(),laydate.getEndDate(new Date().getMonth())-1);

let endDate= laydate.render({
    elem: '#endCreateTime',//选择器结束时间
    type: 'date',
    value : endTime,
    // value : new Date(endTime),
    min:"1970-1-1",//设置min默认最小值
    done: function(value,date){
        startDate.config.max={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        }
    }
});

let startDate=laydate.render({
    elem: '#startCreateTime',
    type: 'date',
    value : startTime,
    // value : new Date(startTime),
    max:"2099-12-31",//设置一个默认最大值
    done: function(value, date){
        endDate.config.min ={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        };
    }
});
form.render();//表单刷新

tableFun();


form.on('submit(submitform)', function(data){
    formTerm = data.field;
    table.reload('drawingstableid',{where:formTerm});
    return false;
});

$("#statistical").on("click",function () {
    parent.intab("views/jsp/other/tpl/statistics.jsp","图纸统计")
});
// 表格渲染
function tableFun() {
    table.render({
        elem: '#drawingsselect'
        ,id: 'drawingstableid'
        ,url: 'blueprint/selectByPage'
        ,method:'post'
        ,where:{
            startCreateTime:$("#startCreateTime").val()||layui.util.toDateString(startTime,"yyyy-MM-dd"),
            endCreateTime:$("#endCreateTime").val()||layui.util.toDateString(endTime,"yyyy-MM-dd")
        }
        ,toolbar: '#drawingstoolbar'
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'number', title:'图纸编号',sort:true,event: "drawingnumber",width: 210}
            ,{field:'createTime', title:'创建日期',sort:true, templet: function(d) {return layui.util.toDateString(d.createTime,"yyyy-MM-dd");} }
            ,{field:'remark', title:'备注'}
            ,{field:'operator', title:'操作员',
                templet: function(data) {
                    var name = "";
                    $.each(userList, function(index, item) {
                        if (data.operator==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            // ,{field:'productcode', title:'产品编码'}
            ,{field:'boxStatus', title:'单据类型', templet: function(data) {
                    switch (data.boxStatus) {
                        case "1": return "草稿箱";
                        case "2": return "待批箱";
                        case "3": return "已批箱";
                        case "4": return "完成箱";
                        case "5": return "垃圾箱";
                    }
                }
            }
            // ,{fixed: 'right', width:240, toolbar: '#drawingseditor', title:'操作'}
            ,{fixed: 'right', width:240, title:'操作',templet: function(d){
                    // 单据状态/类型（1：草稿箱，2：待批箱，3：已批箱，4：完成箱，5垃圾箱）
                    if(isMsn=="是"){//管理员
                        var html="<div>"
                        if(d.boxStatus==1 || d.boxStatus==2){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                        }
                        if(d.boxStatus==1){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if(d.boxStatus==2){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                        }
                        if(d.boxStatus==2 || d.boxStatus==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        }
                        if(d.boxStatus==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        return html+"</div>";
                    }else {
                        var html = "<div>"
                        if (d.boxStatus == 1) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if(d.boxStatus==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        return html + "</div>";
                    }
                }
            }
        ]]
        ,height: $(document).height() - $('#drawingsselect').offset().top - 50
        ,page: true
        // ,limits: [10,20,50]
        // ,limit: 1,
        ,parseData: function(res){
            if(res.msg!=""){
                layer.msg(res.msg, {icon: 3});
            }
        }
    });

    table.on('tool(drawingstable)', function(obj){
        var data = obj.data;
        if(obj.event === 'update') {
            parent.intab("views/jsp/other/tpl/newupdrawings.jsp?id="+obj.data.id,"修改图纸")
            return;
        }
        if(obj.event === 'delect'){
            layer.confirm('确定删除吗', function (index) {
                if(deleteById(data.id)){
                    obj.del();
                    layer.close(index);
                }
            });
            return;
        }
        if(obj.event === 'submits'){
            layer.confirm('确定提交审批吗', function (index) {
                bpmId=startProcess(data.id);
                update(data.id,data.boxStatus*1+1,"提交审批");
            });
            return;
        }
        if(obj.event === 'through'){
            layer.confirm('确定审批通过吗', function (index) {
                update(data.id,data.boxStatus*1+1,"审批通过");
            });
            return;
        }
        if(obj.event === 'backtothe'){
            layer.confirm('确定审批退回吗', function (index) {
                update(data.id,data.boxStatus-1,"审批退回");
            });
            return;
        }
        if(obj.event === 'complete'){
            layer.confirm('确定完成吗', function (index) {
                update(data.id,data.boxStatus*1+1,"审批完成");
            });
            return;
        }
        if(obj.event === 'reduction'){
            layer.confirm('确定还原吗', function (index) {
                update(data.id,1,"审批还原");
            });
            return;
        }
        if (obj.event === "drawingnumber"){
            parent.intab("views/jsp/other/tpl/viewdrawings.jsp?id="+obj.data.id,"图纸明细");
            return;
        }
    });

    table.on('toolbar(drawingstable)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
            case 'news':
                parent.intab("views/jsp/other/tpl/newupdrawings.jsp","新增图纸")
                break;
            case 'dels':
                var data=checkStatus.data,delList=[];
                data.forEach(function(n,i){
                    delList.push(n.id);
                });
                if(delList!=''){
                    layer.confirm('确定删除所选项吗？',function (index) {
                        deleteByIdList(delList);
                    })
                }else{
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

}
//获取全部操作员
function getAllUser() {
    var obj={};
    $.ajax({
        async :false,
        type : 'POST',
        url:'user/getAllUserNameAndCode',
        dataType:"json",
        contentType: 'application/json;charset=utf-8',
        success : function (res) {
            if(res.status==200 ){
                if (res.data.length>0){
                    obj = res.data;
                    $("#operatorCode").empty();
                    $("#operatorCode").append(new Option("全部",'')); //设置默认值
                    $.each(res.data, function(index, item) {
                        $("#operatorCode").append(new Option(item.name,item.code));
                    });
                } else {
                    $("#operatorCode").append(new Option("暂无数据", ""));
                }
            }
        },
        error: function(data) {
            layer.msg("获取失败!");
        }
    });
    return obj;
}

function deleteById(delId) {
    var tf = false;
    $.ajax({
        type: 'POST',
        url: 'blueprint/delete/'+delId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                if(da.data){
                    tf = true;
                    layer.msg("删除成功",{icon: 1});
                    tableFun();
                }else{
                    layer.msg("删除失败",{icon: 4});
                }
            }else{
                layer.msg("删除失败",{icon: 2});
            }
        },
        error: function (data) {
            layer.msg("删除异常",{icon: 5});
        }
    });
    return tf;
}

function deleteByIdList(idList) {
    var ids = {"idList":idList};
    var tf = false;
    $.ajax({
        type: 'POST',
        data: JSON.stringify(ids),
        url: 'blueprint/deleteByIdList',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                if(da.data){
                    tf = true;
                    layer.msg("删除成功!");
                    tableFun();
                }else{
                    layer.msg("删除失败!");
                }
            }else{
                layer.msg("请求失败!");
            }
        },
        error: function (data) {
            layer.msg("删除失败!");
        }
    });
    return tf;
}

//boxStatus 1 草稿 2 待批  3:已批 4 完成 5 垃圾
function update(id,boxStatus,titleName) {
    var tf = false;
    var msgInfo = "";
    var dataJson = {
        "id":id,
        "boxStatus":boxStatus,
        "bpmId":bpmId,
        "bpmStatus":bpmStatus,
    };
    $.ajax({
        type: 'POST',
        data: JSON.stringify(dataJson),
        url: 'blueprint/updateBoxStatusBykey',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = true;
                msgInfo = titleName+"成功!"
                table.reload('drawingstableid');
                // blueprintListTable();
            }else{
                msgInfo = titleName+"失败!"
            }
        },
        error: function (data) {
            msgInfo = titleName+"异常!"
        }
    });
    layer.msg(msgInfo);
    return tf;
}

function startProcess(bid) {
    let res="";
    $.ajax({
        type : 'get',
        data:{"processDefId":'blueprint',"bid":bid,"variables":null},
        url:'process/startProcess',
        async:false,
        dataType:"json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}